<?php

namespace app\home\controller;

use app\home\model\Idfa724Model;
use app\home\model\Order;
use app\home\service\NotifyService;
use app\home\service\OrderService;
use think\Db;
use think\helper\hash\Md5;
use think\Model;
use think\Request;
use think\response\Json;

class Pay800012 extends BasePay{

    const  PUBLIC = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAp/UwTAYROd11d09xknBvtUtDwzTaYxMVPF2vt8gJwGBBHBZgvRdvWdV6rLFr0i8r5+h3bmzKGzeAMYz4OyFk9EwBw4TBCfu+3IrDDZ9+eyx+U/REPf5iebA7klzfOhM8dEsdaE2XcEf3/LWb0gF9IylMEVUhE18Pn04Z1P0PRx/RgT7Fj47fMyBcH7U8XtRg5zc1hJEk0hp3MnejR62pjTtef+4jjL6zW1gWXkIO9DrGvgDR9O90AQVmhmoqtrbzJYWGTJ/1hgfzPZMUlYiFgYrnuMG/eXa1pUupEDkSJaO6ZP8Ghp+Gb+9gJqJVVAiqNJgOod7684IYM0tWxlThPwIDAQAB';
    const  PRIVATE = '2D6R62VSDUWXBOBYN4YVPASIBCZWYBNQ532TP52OB3A5H5UZBY4QA6XR';

    
    

    public function __construct()
    {
        header('Content-Type: text/html;charset=utf-8');
        header('Access-Control-Allow-Origin:*'); // *代表允许任何网址请求
        header('Access-Control-Allow-Methods:POST,GET,OPTIONS,DELETE'); // 允许请求的类型
        header('Access-Control-Allow-Credentials: true'); // 设置是否允许发送 cookies
        header('Access-Control-Allow-Headers: Content-Type,Content-Length,Accept-Encoding,X-Requested-with, Origin'); // 
    }

    public function order()
    {
        parent::order();
        $params = Request::instance()->param();
        $url = 'https://apichain.catappult.io/transaction/inapp';
        $url .= '?product='.$params['product'];
        $url .= '&domain='.$params['domain'];
        $url .= '&order_reference='.$this->order_array['id'];
        $url .= '&callback_url='.urlencode('https://pay.carcadefishing.com/home/pay800012/notify');
        $signed_url = $url.'&signature='.hash_hmac('sha256', $url, self::PRIVATE, false);

        exit(json_encode(['code'=>1,'msg'=>'','data'=>$signed_url]));
    }

    


    public function notify()
    {
        parent::notify();
        $params = $this->params;
        mylog($params);
        try{
            //验证签名
            $data = json_decode($params['transaction'],true);
            $res = file_get_contents('https://api.catappult.io/broker/8.20220927/transactions/'.$data['uid']);
            if(empty($res)){
                throw new \Exception('获取数据失败');
            }
            
            $resData = json_decode($res,true);
            if($resData['status'] != 'COMPLETED'){
                throw new \Exception('status false');
            }
            //保存第三方单号
            $tradeLog = (new \app\home\model\TradeLog)->where(['id'=>$resData['reference']])->find();
            if (empty($tradeLog)) {
                throw new \Exception('订单不存在');
            }
            $tradeLog->transactionID = $resData['uid'];
            $tradeLog->dollPrice = $resData['price']['usd'];
            $tradeLog->dollPriceType = 'US';
            $tradeLog->save();

            if ($tradeLog['goods_id'] != $resData['product']) {
                throw new \Exception('计费点不一致' . ' 传参:' .  $resData['product'] . ' 实际:' . $tradeLog['goods_id']);
            }
            if ($tradeLog["status"] == OrderService::PAY_STATUS_PAID) {
                mylog("800012 订单已经处理过了 订单id".$tradeLog['id']);
                exit('SUCCESS');
            }
            
            //发货
            $notifyService = new NotifyService();
            if($notifyService->notifyProcess($tradeLog) == false){
                throw new \Exception('notifyProcess false');
            }
            exit('SUCCESS');
        }catch (\Exception $exception){
            mylog('800012-error:'.$exception->getMessage().' line:'.$exception->getLine().' file:'.$exception->getFile());
            exit('FAIL');
        }

    }

    

    
    /**
     * @param $url
     * @param null $body
     * @return bool|string
     * @throws Exception
     */
    protected function curl($url, $body = null)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        // curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json"));
        curl_setopt($ch, CURLOPT_HTTPHEADER,[]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $body);
        //TODO 证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        
        curl_close($ch);
        mylog($response);
        return $response;

        
    }
   
}
